package start.gui;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import jaxb.messages.Folder;

import start.StrongBoxClient;
import virtualHD.VirtualHDException;

public class RoleFrame extends JFrame{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public RoleFrame(StrongBoxClient sbc){
		super("Choose user and new role");
		this.sbc = sbc;
		this.setContentPane(makeRolePanel());
		this.setResizable(false);
		this.setSize(new Dimension(300,200));
	}
	
	private JPanel makeRolePanel(){
		ImagePanel panel = new ImagePanel("/images/permits.jpg",null);
		panel.setLayout(new GridBagLayout());
		
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		panel.add(new JLabel("User: "));
		String folders[] = null;
		try {
			folders = sbc.getUsers();
		} catch (VirtualHDException e1) {
			JOptionPane.showConfirmDialog(this, e1.getCause(), "Warning", JOptionPane.WARNING_MESSAGE);
		}
		c.gridx = 1;
		c.gridy = 0;
		c.fill = GridBagConstraints.HORIZONTAL;
		final JComboBox userList = new JComboBox(folders);
		panel.add(userList,c);
		
		c.gridx = 0;
		c.gridy = 1;
		c.fill = GridBagConstraints.HORIZONTAL;
		panel.add(new JLabel("New role: "),c);
		
		c.gridx = 1;
		c.gridy = 1;
		c.fill = GridBagConstraints.HORIZONTAL;
		String roles[] = {"WRITER","READER","VIEWER"};
		final JComboBox roleList = new JComboBox(roles);
		panel.add(roleList,c);
		
		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 2;
		c.fill  = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(10,0,0,0);
		
		JButton button = new JButton("CHANGE!");
		button.setActionCommand("CHANGE");
		button.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent evt) {
				if(evt.getActionCommand().equals("CHANGE")){
					Folder folder = new Folder();
					folder.setUserid((String)userList.getSelectedItem());
					folder.setRole((String)roleList.getSelectedItem());
					
					try {
						sbc.change_role(folder);
						JOptionPane.showMessageDialog(null, "Role of "+folder.getUserid()+" changed to "
								+folder.getRole()+"!");
					} catch (VirtualHDException e) {
						JOptionPane.showMessageDialog(null, 
								e.getMessage(),
								"ERROR",
								JOptionPane.ERROR_MESSAGE
						);
					}
				}
				
			}
			
		});
		
		panel.add(button,c);
		return panel;
		
	}
	
	private StrongBoxClient sbc;

}
